package com.sxx.beautifulcity.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.sxx.beautifulcity.R;
import com.sxx.beautifulcity.adapter.BarbecueAdapter;
import com.sxx.beautifulcity.database.BarbecueHelper;
import com.sxx.beautifulcity.dialog.CommonProgressDialog;
import com.sxx.beautifulcity.entity.greendao.BarbecuteDaoEntity;
import com.sxx.beautifulcity.constant.Constant;
import com.sxx.beautifulcity.listenerInterface.OnBarbecuteItemClickListener;
import com.sxx.beautifulcity.utils.VolleySingleton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dllo on 15/10/31.
 * 搜索界面中的烧烤界面
 */
public class BarbecueActivity extends AppCompatActivity implements View.OnClickListener, OnBarbecuteItemClickListener {
    //定义RecyclerView
    private RecyclerView barbecue_recyclerview;
    //定义适配器
    private BarbecueAdapter adapter;
    private TextView titleTv;
    private Button editBtn;
    private ImageView backIv;
    //定义数据库帮助类
    private BarbecueHelper helper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recyclerview_barbecue);
        init();
        helper = new BarbecueHelper();
        //查询数据库
        List<BarbecuteDaoEntity> entities = helper.queryBarbecuteAll();
        if (entities.size() == 0) {
            requestCount();
        } else {
            adapter.addData(entities);
        }

    }

    /**
     * 初始化数据
     */
    private void init() {

        titleTv = (TextView) findViewById(R.id.titleTv);
        titleTv.setText("烧烤");
        backIv = (ImageView) findViewById(R.id.backIV);
        editBtn = (Button) findViewById(R.id.editBtn);
        backIv.setOnClickListener(this);
        editBtn.setOnClickListener(this);
        adapter = new BarbecueAdapter();

        barbecue_recyclerview = (RecyclerView) findViewById(R.id.barbecue_recyclerview);
        GridLayoutManager manager = new GridLayoutManager(this, 1);
        barbecue_recyclerview.setLayoutManager(manager);
        barbecue_recyclerview.setAdapter(adapter);
        adapter.OnBarbecuteItemClickListener(this);
    }

    /**
     * 请求网络数据
     */
    private void requestCount() {
        final Dialog dialog = CommonProgressDialog.createLoadingDialog(this , "Loding......");
        dialog.show();
        String path = Constant.BARBECUTE_URL;
        JsonObjectRequest request = new JsonObjectRequest(path, null,
                new Response.Listener<JSONObject>() {
                    Gson gson = new Gson();
                    List<BarbecuteDaoEntity> datas = new ArrayList<>();

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.i("hdsfhdklg", response + "");
                        if (response != null && response.has("list_data")) {
                            try {
                                JSONArray array = response.getJSONArray("list_data");
                                for (int i = 0; i < array.length(); i++) {
                                    String str = array.getString(i);
                                    BarbecuteDaoEntity data = gson.fromJson(str, BarbecuteDaoEntity.class);
                                    Log.i("hhjdfhhdshkg", data + "");
                                    datas.add(data);
                                }
                                adapter.addData(datas);
                                helper.deleteBarbecuteList(datas);
                                helper.savaBarbecuteList(datas);
                                dialog.dismiss();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                    }
                }) {
            //添加请求头
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("Accept-Encoding", "");
                return map;
            }
        };
        VolleySingleton.getInstance().addRequest(request);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.backIV:
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finish();
                overridePendingTransition(R.anim.left_out, R.anim.right_into);
                break;

            case R.id.editBtn:
                showPopupMenu(editBtn);
                break;

        }
    }


    /***
     * 弹出一个菜单
     */
    public void showPopupMenu(View anchor) {
        PopupMenu pm = new PopupMenu(this, anchor);
        // 加载菜单文件
        pm.inflate(R.menu.menu_main);

        // 设置菜单项的点击事件
        pm.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                // TODO Auto-generated method stub

                if (item.getItemId() == R.id.giveupItem) {

                } else if (item.getItemId() == R.id.mergeItem) {

                } else if (item.getItemId() == R.id.otherItem) {

                }
                return false;
            }
        });
        pm.show();// 显示菜单
    }

    @Override
    public void OnBarbecuteItemClick(BarbecuteDaoEntity data) {
        Intent intent = new Intent();
        intent.putExtra("Srcurl" , data.getSrcurl());
        intent.setClass(this, BarbecuteDetailActivity.class);
        Log.i("hjjdsgvkld", data.getSrcurl());
        startActivity(intent);
        finish();
        overridePendingTransition(R.anim.left_out, R.anim.right_into);
    }
}
